package com.example.receivermsg.message;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * ClassName:MessageReceive
 * Package:com.example.receivermsg.message
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/8/13-13:47
 * @Version:v1.0
 */
@Component
@Slf4j
public class MessageReceive {


    /**
     * 对正常队列接收消息，但不对其进行确认
     *
     * @param message
     */
    @RabbitListener(queues = {"queue.normal.4"})
    public void receiveMsg(Message message, Channel channel) {

        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的唯一标识
        long deliveryTag = messageProperties.getDeliveryTag();


        try {
            byte[] body = message.getBody();
            String str = new String(body);
            log.info("接收到的消息为:{}", str);
            //TODO 业务逻辑处理
            int a = 1 / 0;
            //消费者的手动确认, false 只确认当前消息 ,改为true为批量确认
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("接受者出现问题:{}", e.getMessage());
            try {
                //消费者的手动不确,重新入队(最后一个参数) 不会进入死信队列
                //channel.basicNack(deliveryTag, false, true);

                //参数三不重新入队,进入死信队列
                channel.basicNack(deliveryTag, false, false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}
